<template>
  <div class="m-[25px_15px] md:m-[25px_40px] xl:m-[50px]">
    <div class="flex items-center mb-[15px] xl:mb-4">
      <select
        class="p-[8px_35px_8px_15px] text-[13px] text-white bg-secondary bg-[url('@/assets/images/select-arrow.svg')] bg-no-repeat bg-[100%_45%] bg-[length:30px_60px] border-secondary appearance-none rounded-[0] disabled:cursor-default disabled:opacity-40 mr-[10px]"
        v-if="seasons.length > 1"
        v-model="activeSeason"
        @change="getEpisodes"
      >
        <option
          v-for="season in seasons"
          :key="`season-${season.season}`"
          :value="season.season"
        >
          Season {{ season.season }}
        </option>
      </select>

      <strong v-if="activeEpisodes" class="text-xs text-grey xl:text-sm">
        {{ episodeCount }}
      </strong>
    </div>

    <div v-if="activeEpisodes" class="flex flex-wrap mx-[-4px]">
      <EpisodesItem
        class="w-full p-1 md:w-[calc(100%/2)] lg:w-[calc(100%/3)] xl:w-[calc(100%/4)] 2xl:w-[calc(100%/5)]"
        v-for="episode in activeEpisodes"
        :key="`episode-${episode.id}`"
        :episode="episode"
      />
    </div>
  </div>
</template>
<script setup>
import { ref, computed } from "vue";
import EpisodesItem from "./EpisodesItem.vue";
import { getTvShowEpisodes } from "@/api";
import { useRoute } from "vue-router";

const { numberOfSeasons } = defineProps({
  numberOfSeasons: {
    type: Number,
    required: true,
  },
});
const route = useRoute()
const activeEpisodes = ref(null);
const activeSeason = ref(numberOfSeasons);

const episodeCount = computed(() => {
  return `${activeEpisodes.value?.length} ${
    activeEpisodes.value?.length > 1 ? "Episodes" : "Episode"
  }`;
});

const seasons = computed(() => {
  const seasons = [];
  for (let index = 0; index < numberOfSeasons; index++) {
    seasons.push({
      season: index + 1,
      episodes: null,
    });
  }
  seasons.sort((a, b) => (a.season > b.season ? -1 : 1));
  return seasons;
});
const getEpisodes = () => {
  const season = seasons.value.find(
    (season) => season.season === activeSeason.value
  );
  if (season.episodes) {
    activeEpisodes.value = season.episodes;
  } else {
    getTvShowEpisodes(route.params.id,activeSeason.value).then((res) => {
      season.episodes = res.episodes;
      activeEpisodes.value = season.episodes;
    });
  }
};

getEpisodes();
</script>
